//
//  LightToningViewController.m
//  MicrowaveLight
//
//  Created by Kendama on 2017/6/16.
//  Copyright © 2017年 DT. All rights reserved.
//

#import "LightToningViewController.h"
#import "CircleSliderView.h"
#import "ReNameOfDeviceApi.h"
#import "MicrophoneAlertView.h"
#import "TEAChart.h"
#import <AVFoundation/AVFoundation.h>
#define ColorArrayHigh @[@"128,0,255",@"0,0,255",@"0,255,255",@"0,255,0",@"255,255,0",@"255,128,0",@"255,0,0"]

@interface LightToningViewController ()

/** 圆形灯光调色板 **/
@property(nonatomic,strong) CircleSliderView *circleSliderView;

/** 灯泡名称 **/
@property(nonatomic,strong) UIButton *lightNameButton;
@property(nonatomic,strong) UIColor *lightColor;


/** 亮度 **/
@property(nonatomic,strong) UISlider *brightnessSlider;
@property(nonatomic,strong) UILabel *brightnessLabel;
@property(nonatomic,assign) NSInteger brightness;

/** 色温 **/
@property(nonatomic,strong) UISlider *colorTemperatureSlider;
@property(nonatomic,strong) UILabel *colorTemperatureLabel;
@property(nonatomic,assign) NSInteger colorTemperature;

/** 闪烁频率 **/
@property(nonatomic,strong) UISlider *twinkleSlider;
@property(nonatomic,strong) UILabel *twinkleLabel;
@property(nonatomic,assign) NSInteger twinkle;

/** 音乐律动 **/
@property(nonatomic,strong) UIButton *musicButton;
/** 麦克风律动 **/
@property(nonatomic,strong) UIButton *microphoneButton;

/** 角度 **/
@property(nonatomic,assign) NSInteger angle;
/** 麦克风接受器 **/
@property(nonatomic,strong) AVAudioRecorder *recorder;
/** 麦克律动弹窗 **/
@property(nonatomic,strong) MicrophoneAlertView *alertView;
/** 定时器 **/
@property (nonatomic, strong)dispatch_source_t timer;
/** 控制指令时间戳，0.5秒发送一次 **/
@property(nonatomic,assign) NSTimeInterval timeInterval;
@end

@implementation LightToningViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(deviceStateChange:) name:@"DeviceStateNotification" object:nil];
    
}

- (void)refreshBaseControlValue {
    [self setNavigationBarTitle:@"灯泡调色"];
    [self hideNavigationBottomLine];
    self.view.backgroundColor = [UIColor colorWithRed:52/255.0 green:52/255.0 blue:52/255.0 alpha:1];
    [self setRightButtonImage:[UIImage imageNamed:@"nav_update"]];
    [self masLayoutSubviews];
 
    [self updateDeviceState];
}


#pragma mark -- 固件升级
- (void)onRightButtonClick:(id)sender {
    [SVProgressHUD showWithStatus:@"正在检查版本更新..."];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[DTCloudManager defaultJNI_iOS_SDK] getFirmwareVersionByMacAddress:self.deviceModel.mac Callback:^(NSDictionary *dic) {
            MAIN((^{
                [SVProgressHUD dismiss];
                if ([dic[@"errcode"] isEqualToString:@"0"]) { // 有新版本
                    
                    [[AlertViewManager shareManager]initWithMessage:@"有新的固件版本，是否更新固件" cancleButtonTitle:@"取消" OtherButtonsArray:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex, UIAlertView *alertView) {
                        if (buttonIndex == 1) {
                            //                           NSLog(@"更新系统");
                            [self updateFirmwareVersions];
                        }
                    }];
                } else if ([dic[@"errcode"] isEqualToString:@"1"]) { // 设备正在进行固件升级
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                } else if ([dic[@"errcode"] isEqualToString:@"2"]) { // 固件已是最新版本
                    [SVProgressHUD showSuccessWithStatus:dic[@"errmsg"]];
                } else {
                    [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                }
                
            }));
            
        }];
    });

}

- (void)updateFirmwareVersions{
    [SVProgressHUD showWithStatus:@"正在升级中，预计需要三分钟，请耐心等候。"];
    
    [[DTCloudManager defaultJNI_iOS_SDK] updateFirmwareVersionByMacAddress:self.deviceModel.mac Callback:^(NSDictionary *dic) {
        MAIN((^{
            //            [SVProgressHUD dismiss];
            [SVProgressHUD showWithStatus:dic[@"errmsg"]];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
        }));
    }];
}

- (void)updateDeviceState {
    [[DTCloudManager defaultJNI_iOS_SDK]sendCommandByFunctionCode:@"1002" functionCommand:@"" deviceMacAddress:self.deviceModel.mac];
    NSLog(@"发送状态:%i",[[DTCloudManager defaultJNI_iOS_SDK]sendCommandByFunctionCode:@"1002" functionCommand:@"" deviceMacAddress:CurrentDevice.macAddress]);
}

- (void)deviceStateChange:(NSNotification *)notify{
    NSString *content = notify.object;
    NSDictionary *dic = notify.userInfo;
    if ([dic[@"backCode"] isEqualToString:@"1802"] || [dic[@"backCode"] isEqualToString:@"1801"]){ // 查询
        NSString *string = [NSString string];
        if (content.length == 86) {
            string = [content substringWithRange:NSMakeRange(4, 10)];
        } else if (content.length == 12) {
            string = [content substringWithRange:NSMakeRange(2, 10)];
        }
        [self initDeviceStateWithString:string];
    }
    
}

- (void) initDeviceStateWithString:(NSString *)string {
 
    if (string.length == 6) {
        NSString *colorString = [string substringWithRange:NSMakeRange(0, 6)];
        // 灯光颜色
        [self getColorByHexString:colorString result:^(UIColor *color, CGFloat saturation, CGFloat brightness,CGFloat hue) {
            self.circleSliderView.imageColor = color;
            //        self.circleSliderView.angle = hue*360;
            NSLog(@"hue=%f",hue*360);
            
            self.colorTemperatureSlider.value = (int)(saturation*100);
            self.colorTemperatureLabel.text = [NSString stringWithFormat:@"%i%%",(int)(saturation*100)];
            self.colorTemperature = (int)(saturation*100);
            
            self.brightnessSlider.value = (int)(brightness*100);
            self.brightnessLabel.text = [NSString stringWithFormat:@"%i%%",(int)(brightness*100)];
            self.brightness = (int)(brightness*100);
        }];
        
        NSString *twinkleValue = [string substringWithRange:NSMakeRange(8, 2)];
        self.twinkleSlider.value = [twinkleValue intValue];
        self.twinkleLabel.text = [NSString stringWithFormat:@"%@",[self getTwinkleWithSliderValue:[twinkleValue intValue]]];
        self.twinkle = [twinkleValue intValue];
    }


}

// 将16进制颜色转换成UIColor，再取反，获得颜色、亮度、色温
- (void)getColorByHexString:(NSString *)hexString result:(void(^)(UIColor *color,CGFloat saturation, CGFloat brightness,CGFloat hue))result{
    UIColor *originalColor = [UIColor colorWithHexString:[NSString stringWithFormat:@"#%@",hexString]];
    CGFloat hue;
    CGFloat saturation;
    CGFloat brightness;
    CGFloat alpha;
    CGFloat red;
    CGFloat green;
    CGFloat blue;
    // RGB取反
    [originalColor getRed:&red green:&green blue:&blue alpha:&alpha];
    UIColor *negationColor = [UIColor colorWithRed:1-red green:1-green blue:1-blue alpha:1];
    // 取出亮度和色温
    [negationColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    UIColor *color = [UIColor colorWithHue:hue saturation:1 brightness:1 alpha:1];
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
//    NSLog(@"原始颜色：%f,%f,%f\n转换颜色：%f,%f,%f",red,green,blue,1-red,1-green,1-blue);
    result([UIColor colorWithRed:red green:green blue:blue alpha:alpha],saturation,brightness,hue);
}

// 控制灯光效果
- (void)controlLightColorWithColor{
    CGFloat red;
    CGFloat green;
    CGFloat blue;
    CGFloat alpha;
    CGFloat hue;
    CGFloat saturation;
    CGFloat brightness;
    [self.lightColor getRed:&red green:&green blue:&blue alpha:&alpha];

    // 转换成HSB添加亮度和色温
    [self.lightColor getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    brightness = (CGFloat)self.brightness/100;
    saturation = (CGFloat)self.colorTemperature/100;
    UIColor *controlColor = [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:alpha];
    [controlColor getRed:&red green:&green blue:&blue alpha:&alpha];
    // 颜色取反
//    red = 1 - red;
//    green = 1 - green;
//    blue = 1 - blue;
//    UIColor *negationColor = [UIColor colorWithRed:1-red green:1-green blue:1-blue alpha:alpha];
    int rgb = (int) (red * 255.0f)<<16 | (int) (green * 255.0f)<<8 | (int) (blue * 255.0f)<<0;
    NSString *string = [NSString stringWithFormat:@"01%06x100%li", rgb,(long)self.twinkle];
    [[DTCloudManager defaultJNI_iOS_SDK]sendCommandByFunctionCode:@"1001" functionCommand:string deviceMacAddress:self.deviceModel.mac];
    NSLog(@"颜色：%@",string);

}



#pragma mark -- 事件
- (void)onBrightnessThumb:(UISlider *)sender{
    NSString *brightness = [NSString stringWithFormat:@"%i%%",(int)sender.value];
    self.brightnessLabel.text = brightness;
//    self.senceModel.brightness = [NSString stringWithFormat:@"%i",(int)sender.value];
    
}
- (void)endBrightnessThumb:(UISlider *)sender{
    self.brightness = (int)sender.value;
    [self controlLightColorWithColor];
}

- (void)onColorTemperatureThumb:(UISlider *)sender{
    NSString *colorTemperature = [NSString stringWithFormat:@"%i%%",(int)sender.value];
    self.colorTemperatureLabel.text = colorTemperature;
//    self.senceModel.colour_temperature = [NSString stringWithFormat:@"%i",(int)sender.value];
    
}
- (void)endColorTemperatureThumb:(UISlider *)sender{
    self.colorTemperature = (int)sender.value;
    [self controlLightColorWithColor];

}

- (void)onTwinkleThumb:(UISlider *)sender{
    NSString *twinkle = [self getTwinkleWithSliderValue:sender.value];
    self.twinkleLabel.text = twinkle;
//    self.senceModel.twinkle = [NSString stringWithFormat:@"%i",(int)sender.value];
    
}

- (void)endTwinkleThumb:(UISlider *)sender{
    self.twinkle = (int)sender.value;
    [self controlLightColorWithColor];

}

- (NSString *)getTwinkleWithSliderValue:(NSInteger)value {
    NSString *string = [[NSString alloc] init];

    switch (value) {
            break;
        case 0:
            string = @"0";
            break;
        case 1:
            string = @"0.1s";
            break;
        case 2:
            string = @"0.25s";
            break;
        case 3:
            string = @"0.5s";
            break;
        case 4:
            string = @"1s";
            break;
        case 5:
            string = @"2s";
            break;
        default:
            break;
    }
    return string;
}

- (void)didClickLightNameButton{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请输入灯泡名称" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    UITextField *nickFeild = [alert textFieldAtIndex:0];
    nickFeild.font = [UIFont systemFontOfSize:11];
    nickFeild.placeholder = @"请在此处输入灯泡名称";
    alert.tag = 200;
    [alert show];
}


- (void)didClickMusicButton{
    UIView *superView = self.view;
    self.alertView  = [[MicrophoneAlertView alloc]init];
    [superView addSubview:self.alertView];
    __weak typeof(self) weakSelf = self;
    self.alertView .cancel_block = ^(UIButton *sender) {
        dispatch_cancel(weakSelf.timer);
    };
    [self.alertView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    self.alertView.barChart.max = 120;
    self.alertView.barChart.autoMax = NO;
    self.alertView.barChart.barColor = [UIColor colorWithRed:31/255.0 green:189/255.0 blue:188/255.0 alpha:1];
//    self.alertView.barChart.data = @[@2, @7, @1, @8, @2, @8, @2, @7, @1, @8, @2, @8, @2, @7, @1, @8, @2, @8];
    [self.alertView callinAnimation];

    
    [[AVAudioSession sharedInstance]
     setCategory: AVAudioSessionCategoryPlayAndRecord error:nil];
    
    /* 不需要保存录音文件 */
    NSURL *url = [NSURL fileURLWithPath:@"/dev/null"];
    
    NSDictionary *settings = [NSDictionary dictionaryWithObjectsAndKeys:
                              [NSNumber numberWithFloat: 44100.0], AVSampleRateKey,
                              [NSNumber numberWithInt: kAudioFormatAppleLossless], AVFormatIDKey,
                              [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                              [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
                              nil];
    
    NSError *error;
    self.recorder = [[AVAudioRecorder alloc] initWithURL:url settings:settings error:&error];
    if (self.recorder )
    {
        [self.recorder  prepareToRecord];
        self.recorder .meteringEnabled = YES;
        [self.recorder  record];
        NSTimeInterval period = 0.1; //设置时间间隔
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(self.timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(self.timer, ^{
            [self levelTimerCallback];
        });
        dispatch_resume(self.timer);
    }
    else
    {
        NSLog(@"%@", [error description]);
    }

}

- (void)didClickMicrophoneButton{

}

/* 该方法确实会随环境音量变化而变化，但具体分贝值是否准确暂时没有研究 */
- (void)levelTimerCallback {
    [self.recorder  updateMeters];
    
    float   level;                // The linear 0.0 .. 1.0 value we need.
    float   minDecibels = -80.0f; // Or use -60dB, which I measured in a silent room.
    float   decibels    = [self.recorder averagePowerForChannel:0];
    
    if (decibels < minDecibels)
    {
        level = 0.0f;
    }
    else if (decibels >= 0.0f)
    {
        level = 1.0f;
    }
    else
    {
        float   root            = 2.0f;
        float   minAmp          = powf(10.0f, 0.05f * minDecibels);
        float   inverseAmpRange = 1.0f / (1.0f - minAmp);
        float   amp             = powf(10.0f, 0.05f * decibels);
        float   adjAmp          = (amp - minAmp) * inverseAmpRange;
        
        level = powf(adjAmp, 1.0f / root);
    }
    
    /* level 范围[0 ~ 1], 转为[0 ~120] 之间 */
    dispatch_async(dispatch_get_main_queue(), ^{
//        NSLog(@"声音:%@",[NSString stringWithFormat:@"%f", level*120]);
        NSInteger mainValue = level*120;
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:18];
        for (int i = 0; i < 18; i++) {
            NSNumber *value = [NSNumber numberWithInt:arc4random() % mainValue];
            [array addObject:value];
        }
        self.alertView.barChart.data = array;
        NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
        NSTimeInterval time = [dat timeIntervalSince1970];
        if (time > self.timeInterval + 1) { // 超过多少秒才发送控制指令
            [self sendTheDataByListMusicData:level];
            self.timeInterval = time;
        }
    });
}

#pragma mark 根据音量变化颜色
- (void)sendTheDataByListMusicData:(float)wave{
    
    NSString *rgbString = @"0,0,0";
    int light = 0;
     CGFloat value = wave * 58;

    if (value > 0 && value < 7) {
        rgbString = ColorArrayHigh[0];
        light = 7;
    }else if (value > 7 && value < 14) {
        rgbString = ColorArrayHigh[6];
        light = 14;
    }else if (value > 14 && value < 20) {
        rgbString = ColorArrayHigh[1];
        light = 20;
    }else if (value > 20 && value < 26) {
        rgbString = ColorArrayHigh[5];
        light = 26;
    }else if (value > 26 && value < 31) {
        rgbString = ColorArrayHigh[2];
        light = 31;
    }else if (value > 31 && value < 36) {
        rgbString = ColorArrayHigh[4];
        light = 36;
    }else if (value > 36 && value < 40) {
        rgbString = ColorArrayHigh[3];
        light = 40;
    }else if (value > 40 && value < 44) {
        rgbString = ColorArrayHigh[3];
        light = 44;
    }else if (value > 44 && value < 47) {
        rgbString = ColorArrayHigh[4];
        light = 47;
    }else if (value > 47 && value < 50) {
        rgbString = ColorArrayHigh[2];
        light = 50;
    }else if (value > 50 && value < 52) {
        rgbString = ColorArrayHigh[5];
        light = 52;
    }else if (value > 52 && value < 54) {
        rgbString = ColorArrayHigh[1];
        light = 54;
    }else if (value > 54 && value < 55) {
        rgbString = ColorArrayHigh[6];
        light = 55;
    }else if (value > 55 && value < 56) {
        rgbString = ColorArrayHigh[0];
        light = 56;
    }
    
    
    
    int r = [[[rgbString componentsSeparatedByString:@","]objectAtIndex:0]intValue];
    int g = [[[rgbString componentsSeparatedByString:@","]objectAtIndex:1]intValue];
    int b = [[[rgbString componentsSeparatedByString:@","]objectAtIndex:2]intValue];
    NSLog(@"颜色RGB：%i,%i,%i",r,g,b);
    CGFloat brightness = (CGFloat)light/65;
    UIColor *color = [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1];
    [self voiceControlLightColorWithColor:color light:brightness];

}


- (void)voiceControlLightColorWithColor:(UIColor *)color light:(CGFloat)light{
    CGFloat red;
    CGFloat green;
    CGFloat blue;
    CGFloat alpha;
    CGFloat hue;
    CGFloat saturation;
    CGFloat brightness;
    [color getRed:&red green:&green blue:&blue alpha:&alpha];
    
    // 转换成HSB添加亮度和色温
    [color getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha];
    
    UIColor *controlColor = [UIColor colorWithHue:hue saturation:0.5 brightness:light alpha:alpha];
    [controlColor getRed:&red green:&green blue:&blue alpha:&alpha];
    // 颜色取反
//    red = 1 - red;
//    green = 1 - green;
//    blue = 1 - blue;
    //    UIColor *negationColor = [UIColor colorWithRed:1-red green:1-green blue:1-blue alpha:alpha];
    int rgb = (int) (red * 255.0f)<<16 | (int) (green * 255.0f)<<8 | (int) (blue * 255.0f)<<0;
    NSString *string = [NSString stringWithFormat:@"01%06x100%li", rgb,(long)self.twinkle];
    
#warning 麦克律动只能使用近程
    
    NSInteger state = [[DTCloudManager defaultJNI_iOS_SDK]sendLocalCommandByFunctionCode:@"1001" functionCommand:string deviceMacAddress:self.deviceModel.mac];
    NSLog(@"声音颜色：%@",string);
    if (state == 3) {
        [self.alertView calloutAnimation];
        [SVProgressHUD showErrorWithStatus:@"远程无法使用麦克律动"];
        dispatch_cancel(self.timer);
    }

    
}


#pragma mark  alertView修改昵称事件
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if (buttonIndex == 1)
    {
        switch (alertView.tag)
        {
            case 200:
            {
                //此处向服务器提交修改昵称的请求
                
                UITextField *nickTextField = [alertView textFieldAtIndex:0];
                [nickTextField endEditing:YES];
                if (nickTextField.text.length>12) {
                    [SVProgressHUD showErrorWithStatus:@"名字长度不能超过12个"];
                    return;
                }
                
                if ([NSString isContainsTwoEmoji:nickTextField.text ]) {
                    [SVProgressHUD showErrorWithStatus:@"名字不能使用表情"];
                    return;
                }
                
                [self.lightNameButton setTitle:nickTextField.text forState:UIControlStateNormal];
                [self.lightNameButton setImage:[UIImage imageNamed:@"bianji"] forState:UIControlStateNormal];
                [self.lightNameButton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:5];
                
                ReNameOfDeviceApi *api = [[ReNameOfDeviceApi alloc] initWithDic:@{@"id":self.deviceModel.ID,@"name":nickTextField.text}];
                [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
                    NSDictionary *dic = [request responseJSONObject];
                    if([dic[@"errcode"] intValue] == 0) {
                        [SVProgressHUD showSuccessWithStatus:dic[@"errmsg"]];
                    } else {
                        [SVProgressHUD showErrorWithStatus:dic[@"errmsg"]];
                    }
                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
                    [SVProgressHUD showErrorWithStatus:@"网络错误"];

                }];

                
            }
                break;
            default:
                break;
        }
        
    }
    
}


- (void)masLayoutSubviews{

    __weak UIView *superView = self.view;
    
    [self.lightNameButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(superView).with.offset(64+px1920Height(80));
        make.height.mas_equalTo(px1920Height(60));
        make.width.mas_equalTo(superView);
    }];

    [self.circleSliderView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(superView);
        make.top.equalTo(self.lightNameButton.mas_bottom).with.offset(px1920Height(80));
        make.height.width.mas_equalTo(px1080Width(675));
    }];
    
    [self.musicButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.circleSliderView.mas_bottom).with.offset(px1920Height(40));
        make.centerX.equalTo(superView);
        make.height.width.mas_equalTo(px1080Width(144));
    }];
    
//    CGFloat padding = px1080Width(300);
//    NSMutableArray *views = [NSMutableArray array];
//    [views addObjectsFromArray:@[self.musicButton,self.microphoneButton]];
//    [views mas_distributeViewsAlongAxis:MASAxisTypeHorizontal withFixedItemLength:px1080Width(144) leadSpacing:padding tailSpacing:padding];
//    [views mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.circleSliderView.mas_bottom).with.offset(px1920Height(40));
//        UIView *blueView = (UIView *)views[0];
//        make.height.mas_equalTo(blueView.mas_width);
//    }];
    
    
    
    int count = 3;
    UIView *lastView = nil;
    NSArray *sliderArray = @[self.brightnessSlider,self.colorTemperatureSlider,self.twinkleSlider];
    NSArray *labelArray = @[self.brightnessLabel,self.colorTemperatureLabel,self.twinkleLabel];
    NSArray *labelTitleArray = @[@"亮度",@"色温",@"闪烁频率"];

    for(int i = 0;i < count;++i ){
        //创建一个View
        
        UILabel *title = [[UILabel alloc] init];
        title.font = [UIFont systemFontOfSize:15];
        title.textColor = [UIColor whiteColor];
        title.text = labelTitleArray[i];
        [superView addSubview:title];
        
        CGFloat titleWidth;
        if (i == 2) {
            titleWidth = px1080Width(240);
        } else {
            titleWidth = px1080Width(120);
        }
        
        //向subView添加约束
        [title mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(titleWidth);
            make.height.mas_equalTo(px1080Width(40));
            make.left.equalTo(self.view).with.offset(px1080Width(90));
            
            //判断是否有前一个子View
            if ( lastView ) {
                //如果有前一个View，上边界和前一个View的下边界紧贴
                make.top.mas_equalTo(lastView.mas_bottom).with.offset(px1920Height(140));
            } else {
                //如果没有前一个View，上边界和container的下边界紧贴
                make.top.mas_equalTo(self.musicButton.mas_bottom).with.offset(px1920Height(120));
            }
        }];
        
        [labelArray[i] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(title.mas_centerY);
            make.width.mas_equalTo(px1080Width(150));
            make.height.mas_equalTo(px1080Width(40));
            make.right.equalTo(self.view).with.offset(-px1080Width(90));
        }];
        
        [sliderArray[i] mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.mas_equalTo(title.mas_centerY);
            make.left.mas_equalTo(title.mas_right).with.offset(px1080Width(35));
            make.right.mas_equalTo(superView).with.offset(-px1080Width(250));
            make.height.mas_equalTo(px1080Width(80));
        }];
        
        //保存前一个View
        lastView = title;
    }
    
}




#pragma mark -- 懒加载
- (CircleSliderView *)circleSliderView
{
    if(!_circleSliderView)
    {
        __weak UIView *superView = self.view;
        _circleSliderView = [[CircleSliderView alloc]initWithFrame:CGRectMake(self.view.center.x-125, 64, px1080Width(675), px1920Height(675))];
        [superView addSubview:_circleSliderView];
        _circleSliderView.imageName = @"ring";
        
        __weak typeof(self) weakSelf = self;
        _circleSliderView.returnColorBlock = ^(UIColor *color) {
            weakSelf.lightColor = color;
            NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
            NSTimeInterval time = [dat timeIntervalSince1970];
            if (time > self.timeInterval + 0.5) { // 超过多少秒才发送控制指令
                [weakSelf controlLightColorWithColor];
                weakSelf.timeInterval = time;
            }
//            weakSelf.colorBackgroundView.backgroundColor = color;
        };
    }
    return _circleSliderView;
}



- (UIButton *)lightNameButton
{
    if(!_lightNameButton)
    {
        UIView *superView = self.view;
        _lightNameButton = [[UIButton alloc]init];
        [superView addSubview:_lightNameButton];
        [_lightNameButton setTitle:self.deviceModel.name forState:UIControlStateNormal];
        [_lightNameButton setImage:[UIImage imageNamed:@"bianji"] forState:UIControlStateNormal];
        [_lightNameButton addTarget:self action:@selector(didClickLightNameButton) forControlEvents:UIControlEventTouchUpInside];
        [_lightNameButton layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight imageTitleSpace:15];
//        [_lightNameButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 120)];
//        [_lightNameButton setImageEdgeInsets:UIEdgeInsetsMake(0, 120, 0, 0)];
        
    }
    return _lightNameButton;
}
- (UISlider *)brightnessSlider
{
    if(!_brightnessSlider)
    {
        UIView *superView = self.view;
        _brightnessSlider = [[UISlider alloc]init];
        [superView addSubview:_brightnessSlider];
        _brightnessSlider.minimumValue = 0;
        _brightnessSlider.maximumValue = 100;
        [_brightnessSlider setMinimumTrackTintColor:[UIColor whiteColor]];
        [_brightnessSlider setMaximumTrackTintColor:[UIColor darkGrayColor]];
        [_brightnessSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
        //滑动过程中不断触发事件
        [_brightnessSlider addTarget:self action:@selector(onBrightnessThumb:) forControlEvents:UIControlEventValueChanged];
        //滑动完成后触发事件
        [_brightnessSlider addTarget:self action:@selector(endBrightnessThumb:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _brightnessSlider;
}



- (UISlider *)colorTemperatureSlider
{
    if(!_colorTemperatureSlider)
    {
        UIView *superView = self.view;
        _colorTemperatureSlider = [[UISlider alloc]init];
        [superView addSubview:_colorTemperatureSlider];
        _colorTemperatureSlider.value = 0;
        _colorTemperatureSlider.minimumValue = 0;
        _colorTemperatureSlider.maximumValue = 100;
        [_colorTemperatureSlider setMinimumTrackTintColor:[UIColor whiteColor]];
        [_colorTemperatureSlider setMaximumTrackTintColor:[UIColor darkGrayColor]];
        [_colorTemperatureSlider setThumbImage:[UIImage imageNamed:@"slider"] forState:UIControlStateNormal];
        //滑动过程中不断触发事件
        [_colorTemperatureSlider addTarget:self action:@selector(onColorTemperatureThumb:) forControlEvents:UIControlEventValueChanged];
        //滑动完成后触发事件
        [_colorTemperatureSlider addTarget:self action:@selector(endColorTemperatureThumb:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _colorTemperatureSlider;
}


- (UISlider *)twinkleSlider
{
    if(!_twinkleSlider)
    {
        UIView *superView = self.view;
        _twinkleSlider = [[UISlider alloc]init];
        [superView addSubview:_twinkleSlider];
        //        _flickerFrequencySlider.value = 1.0;
        _twinkleSlider.minimumValue = 0;
        _twinkleSlider.maximumValue = 5;
        [_twinkleSlider setMinimumTrackTintColor:[UIColor whiteColor]];
        [_twinkleSlider setMaximumTrackTintColor:[UIColor darkGrayColor]];
        [_twinkleSlider setThumbImage:[UIImage imageNamed:@"slider2"] forState:UIControlStateNormal];
        //滑动过程中不断触发事件
        [_twinkleSlider addTarget:self action:@selector(onTwinkleThumb:) forControlEvents:UIControlEventValueChanged];
        //滑动完成后触发事件
        [_twinkleSlider addTarget:self action:@selector(endTwinkleThumb:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _twinkleSlider;
}


- (UIButton *)musicButton
{
    if(!_musicButton)
    {
        UIView *superView = self.view;
        _musicButton = [[UIButton alloc]init];
        [superView addSubview:_musicButton];
        [_musicButton setImage:[UIImage imageNamed:@"btn_music"] forState:UIControlStateNormal];
        [_musicButton setImage:[UIImage imageNamed:@"btn_music_sel"] forState:UIControlStateHighlighted];
        [_musicButton addTarget:self action:@selector(didClickMusicButton) forControlEvents:UIControlEventTouchUpInside];

    }
    return _musicButton;
}


- (UIButton *)microphoneButton
{
    if(!_microphoneButton)
    {
        UIView *superView = self.view;
        _microphoneButton = [[UIButton alloc]init];
        [superView addSubview:_microphoneButton];
        [_microphoneButton setImage:[UIImage imageNamed:@"btn_mic"] forState:UIControlStateNormal];
        [_microphoneButton setImage:[UIImage imageNamed:@"btn_mic_sel"] forState:UIControlStateHighlighted];
        [_microphoneButton addTarget:self action:@selector(didClickMicrophoneButton) forControlEvents:UIControlEventTouchUpInside];
    }
    return _microphoneButton;
}

- (UILabel *)brightnessLabel
{
    if(!_brightnessLabel)
    {
        UIView *superView = self.view;
        _brightnessLabel = [[UILabel alloc]init];
        [superView addSubview:_brightnessLabel];
        [_brightnessLabel setFont:[UIFont systemFontOfSize:15]];
        [_brightnessLabel setTextColor:[UIColor whiteColor]];
        _brightnessLabel.textAlignment = NSTextAlignmentRight;
        _brightnessLabel.text = @"0%";
    }
    return _brightnessLabel;
}

- (UILabel *)colorTemperatureLabel
{
    if(!_colorTemperatureLabel)
    {
        UIView *superView = self.view;
        _colorTemperatureLabel = [[UILabel alloc]init];
        [superView addSubview:_colorTemperatureLabel];
        [_colorTemperatureLabel setFont:[UIFont systemFontOfSize:15]];
        [_colorTemperatureLabel setTextColor:[UIColor whiteColor]];
        _colorTemperatureLabel.textAlignment = NSTextAlignmentRight;
        _colorTemperatureLabel.text = @"0%";
    }
    return _colorTemperatureLabel;
}
- (UILabel *)twinkleLabel
{
    if(!_twinkleLabel)
    {
        UIView *superView = self.view;
        _twinkleLabel = [[UILabel alloc]init];
        [superView addSubview:_twinkleLabel];
        [_twinkleLabel setFont:[UIFont systemFontOfSize:15]];
        [_twinkleLabel setTextColor:[UIColor whiteColor]];
        _twinkleLabel.textAlignment = NSTextAlignmentRight;
        _twinkleLabel.text = @"0s";
    }
    return _twinkleLabel;
}

- (AVAudioRecorder *)recorder
{
    if(!_recorder)
    {
        _recorder = [[AVAudioRecorder alloc]init];
    }
    return _recorder;
}


@end
